package com.enzoism.springboot.dive.chapter02;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * 模拟业务场景：处理耗时任务，处理完一个任务返回一个任务结果，响应式
 * supplyAsync、whenComplete使用的都是deamon线程，主线程退出，会导致任务异常关闭
 * @link https://blog.csdn.net/qq_40826106/article/details/88628536
 */
public class ComletableTest {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        ComletableTest demo = new ComletableTest();
        AtomicInteger num = new AtomicInteger();
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        IntStream.range(0, 5).forEach(value -> {
            CompletableFuture.supplyAsync(() -> {
                return demo.do3Second();
            }, executorService).whenComplete((resultStr, throwable) -> {
                num.addAndGet(1);
                System.out.println(resultStr + "-耗时：" + (System.currentTimeMillis() - start));
            });
            CompletableFuture.supplyAsync(() -> {
                return demo.do5Second();
            }, executorService).whenComplete((resultStr, throwable) -> {
                num.addAndGet(1);
                System.out.println(resultStr + "-耗时：" + (System.currentTimeMillis() - start));
            });
        });

        System.out.println("非阻塞 执行完毕");
        while (true) {
            if (num.get() == 10) {
                System.out.println("任务执行完毕！");
                executorService.shutdown();
                break;
            }

        }
    }

    //任务一
    public String do3Second() {
        try {
            System.out.println("正在执行3秒的方法");
            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "##3";
    }

    //任务二
    public String do5Second() {
        try {
            System.out.println("正在执行5秒的方法");
            TimeUnit.SECONDS.sleep(5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "##5";
    }


}